package com.yuanyi.controller;


import com.yuanyi.dao.AdminDao;
import com.yuanyi.entity.Admin;
import com.yuanyi.util.SecurityUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
public class AdminController {

    private static final Logger Log = LoggerFactory.getLogger(AdminController.class);

    @Autowired
    private AdminDao adminDao;

    @PostMapping(value = "/user_login",produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Map<String, Object> userlogin(@RequestParam("username") String username,@RequestParam("password") String password,@RequestParam("code")String code, HttpSession session){
        System.out.println(username+password+"/////////////////////////////////");
        Admin admin = this.adminDao.findAdminByUsernameAndPassword(username,password);
        Map<String, Object> map = new HashMap<>();
        map.put("verifyCode",(code.equalsIgnoreCase((String)session.getAttribute("code"))));
        map.put("admin", admin);
        map.put("success", (admin != null));
        Log.debug(admin + "-----------");
        return map;
    }

    //获取验证码
    @RequestMapping(value = "/getcode",produces ="application/json;utf-8" )
    @ResponseBody
    public void getSecurityCode(HttpServletResponse response, HttpServletRequest request){
        // 通知浏览器不要缓存
        response.setHeader("Expires", "-1");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "-1");
        SecurityUtil util = SecurityUtil.Instance();
        // 将验证码输入到session中，用来验证
        String code = util.getString();
        request.getSession().setAttribute("code", code);
        // 输出打web页面
        try {
            ImageIO.write(util.getImage(), "jpg", response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //修改密码
    @RequestMapping(value = "/changePwd",produces = "application/json;charset=utf-8")
    @ResponseBody
    public boolean changePwd(@ModelAttribute("u")Admin u){
        try {
            System.out.println(">>>>>>>>>>>>>>>"+u.getPassword()+"************"+u.getUsername());
            Admin user = this.adminDao.findAdminById(u.getId());
            user.setPassword(u.getPassword());
            this.adminDao.save(user);
        }catch (Exception e){
            return false;
        }
        return true;
    }
}
